package com.ms.jsf.converter;

import com.ms.jsf.omnifaces.SelectItemsUtils;
import org.primefaces.component.selectonemenu.SelectOneMenu;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.util.StringUtils;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

/**
 * User: gmc
 * Date: 19/03/13
 */
@FacesConverter("dpwcConverter")
public class DpwcJsfConverter implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        return SelectItemsUtils.findValueByStringConversion(context, component, value, this);
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null || "".equals(value)) {
            return null;
        }
        String varName = ((SelectOneMenu) component).getVar();
        String idName = "id" + StringUtils.capitalize(varName);
        BeanWrapper beanWrapper = new BeanWrapperImpl(value);
        Object propertyValue = beanWrapper.getPropertyValue(idName);
        return String.valueOf(propertyValue);
    }
}
